import axios from 'axios';
import storejs from 'storejs';
import store from '@/store/index.js';
import { MessageBox, Message } from 'element-ui';
import { userKeys } from '@/utils/authUtils.js';
import lodash from 'lodash';

//接口基础url
let apiBaseURL = process.env.VUE_APP_BASE_API;

/**
 * 创建 axios 请求实例
 */
const client = axios.create({
    // url = base url + request url
    baseURL: apiBaseURL,
    // send cookies when cross-domain requests
    // withCredentials: true,
    timeout: 15000 // request timeout
});


/**
 * 登录失效，注销并前往登录页
 */
const toLogin = lodash.debounce(function (res){
    store.dispatch("user/loginout");
    Message({
        message: res.message || '请登录！',
        type: 'error',
        duration: 5 * 1000
    });
}, 600, {
    leading: false,
});


/**
 * 请求前拦截器
 */
client.interceptors.request.use(
    config => {
        // 添加token
        let token = storejs.get(userKeys.token);
        if (token) {
            config.headers['satoken'] = token;
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

/**
 * 接口响应后拦截器
 */
client.interceptors.response.use(
    response => {
        const res = response.data;
        // 如果响应码不是200,则接口业务错误
        if (res.code !== 200) {
            // 用户身份相关错误
            if (res.code === 501 || res.code === 502) {
                console.log("用户身份相关错误: ", res);
                toLogin(res);
            } else {
                // 业务错误
                Message({
                    message: res.message || '操作失败，请稍后再试！',
                    type: 'error',
                    duration: 3 * 1000
                })
            }
            return Promise.reject(res || 'Error');
        } else {
            return Promise.resolve(res)
        }
    },
    error => {
        console.log('http 状态码错误 error', error) // for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 3 * 1000
        });
        return Promise.reject(error)
    }
)


export {
    apiBaseURL
};
export default client;


